/**
 * 
 */
package com.roc.web.action.terminal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblDictionaryItem;
import com.roc.pojo.TblDictionaryLayerItem;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IExcelExportService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.Terminal;

/**
 * @author dxpeng
 * 
 */
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/terminal")
public class TermSnImportAction extends PaginationBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	static Logger logger = LogManager.getLogger(TermSnImportAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	private TermSnImportSearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();

	private InputStream excelFile;
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	private IorgService orgService;

	@Autowired
	private IExcelExportService iexcelSerivce;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	ITerminalService terminalService;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	@Action(value = "termQrtInit", results = { @Result(location = "/pages/terminal/termSnImport.jsp") })
	public String termQrtInit() throws Exception {
		org();
		return SUCCESS;
	}

	@Action(value = "queryTerminalPosSN", results = { @Result(name = "success", location = "/pages/terminal/termSnImport.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	// 查询终端
	public String queryTerminalPosSNAction() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (TermSnImportSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new TermSnImportSearchCondition();
			}
		}
		try {
			/*if(Role.AGENT.getCode().equals(op.getRoleType())){//代理商
				 List<Operators> opList=merchantServices.listAllSubMerchants(op.getId());
				 String[]  agentList= new String[opList.size()];
				 for (int i=0;i<opList.size();i++) {
					 
					Operators o=opList.get(i);
					agentList[i]=Long.toString(o.getId());
					
				}
			   searchCondition.setAgentIdList(agentList);

				String agentId= String.valueOf(op.getId());
			   searchCondition.setObj(agentId);
			}else if(Role.AGENT_BUSS.getCode().equals(op.getRoleType())){// 业务员
				 searchCondition.setOpId(String.valueOf(op.getId()));
			}else if(Role.MERCHANT.getCode().equals(op.getRoleType())){// 商户
				 searchCondition.setMerId(String.valueOf(op.getAccountNo()));
			}else if(Role.SFB_AGENT.getCode().equals(op.getRoleType()))//收付宝
			{
				String agentId= String.valueOf(op.getId());
				   searchCondition.setObj(agentId);
				searchCondition.setSfbId("sfb");
			}*/
			org();
			if(op.getRoleType().equals(Role.MARKET_DIRECT.getCode()) ||op.getRoleType().equals(Role.MARKET_LEAD.getCode())){
				addActionError("销售无权限查询");
				return ERROR;
			}
			// 如果当前登录账号是仓库管理员
			if(op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode())){
		        searchCondition.setRoleType(op.getRoleType());// 角色
		        searchCondition.setOperators(op.getAccountNo());//当前登陆账号
			} else {
				Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
		        String superRole= map.get("superRole");
		        String opRealId =map.get("opRealId");
		        searchCondition.setRoleType(superRole);// 角色
		        searchCondition.setOpId(opRealId);//当前人员id
		        searchCondition.setOneOrgCode(op.getOneagentid());//机构
			}
				int rows = pagenitionService.countSQL(searchCondition);
	
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
	
				List<YjPosInfo> posList = new ArrayList<YjPosInfo>();
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						YjPosInfo pos = new YjPosInfo();
						pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));
	
						String brandCode = obj[1] + "";
						String typeCode = obj[2] + "";
						String nameCode = obj[3] + "";
						
						pos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
						pos.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
						pos.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
						
						pos.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
						pos.setIsBind(Terminal.valueOfCode(
								Constance.Null2EmptyTrim(obj[5])).getName());
						pos.setIsUsed(Terminal.valueOfCode(
								Constance.Null2EmptyTrim(obj[6])).getName());
						pos.setMercCode(Constance.Null2EmptyTrim(obj[7]));
						pos.setTermCode(Constance.Null2EmptyTrim(obj[8]));
						pos.setRemark(Constance.Null2EmptyTrim(obj[9]));
						pos.setInDateStr(DateUtil.formatTime(Constance
								.Null2EmptyTrim(obj[10])));
						pos.setOutDateStr(DateUtil.formatTime(Constance
								.Null2EmptyTrim(obj[11])));
						pos.setAgentName(Constance.Null2EmptyTrim(obj[12]));
						if ( !"".equals( Constance.Null2EmptyTrim(obj[13]) ) ){
							pos.setTekId(Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[13])).getName());
						}
						posList.add(pos);
					}
				}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("posList", posList);			
			getRequest().setAttribute("agenid", searchCondition.getAgentId());
			getRequest().setAttribute("selModelCode", searchCondition.getPosName());
			getRequest().setAttribute("oldBandCode", searchCondition.getPosBrand());			
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	private void org() {
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			TblInsInf infs=orgService.queryOrgByOrgCode(logingMerchant.getOrgCode());
			orgList.add(infs);
			/*if(Role.SYSTEM.getCode().equals(logingMerchant.getRoleType())){
				TblInsInf inf = new TblInsInf();
				inf.setInsIdCd("");
				inf.setInsName("--请选择机构--");
				orgList.add(inf);
				List<TblInsInf> list=orgService.queryOrgList();
				orgList.addAll(list);
			}else{
				TblInsInf infs=orgService.queryOrgByOrgCode(logingMerchant.getOrgCode());
				orgList.add(infs);
			}*/

/*			TblDictionaryItem itemBrand = new TblDictionaryItem();
			Map<String,String> brandMap = terminalService.selBrandItemByType(itemBrand);

			List<Map<String,Object>> modelList = new ArrayList<Map<String,Object>>();

			TblDictionaryItem item = new TblDictionaryItem();
			Map<String,String> typeMap = terminalService.selTypeItemByType(item);*/

			getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
			getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
			getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		ActionContext.getContext().put("merchantList", null);
	}

	protected void dealWithTheListSpecially(List<Object> list) {
		super.dealWithTheListSpecially(list);
		Map<String, String> roleTypes = ConfigProperties
				.getRoleTypeProperties();
		List<Object> tempList = new ArrayList<Object>();
		for (Object obj : list) {
			YjPosInfo pos = (YjPosInfo) obj;
			for (TblInsInf bean : orgList) {
				if (pos.getOrgCode().equals(bean.getInsIdCd())) {
					pos.setOrgName(bean.getInsName());
				}
			}

			tempList.add(pos);
		}
		searchRsList = tempList;
	}

	// 导出excel
	@Action(value = "excelTerminalPosSN", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String settingExcelqQuery() throws Exception {

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String[] headArray = { "终端序列号", "商户号", "终端号", "所属代理商", "品牌", "型号","机型",
				"是否已绑定", "是否已出库", "备注", "入库时间", "出库时间", "是否有效" };
		String reportName = "终端序列号查询";
		try {
			
			Operators op = (Operators) ActionContext.getContext()
			.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
			
			
			if (searchCondition == null) {
				searchCondition = (TermSnImportSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new TermSnImportSearchCondition();
				}
			}
			org();
			if(op.getRoleType().equals(Role.MARKET_DIRECT.getCode()) ||op.getRoleType().equals(Role.MARKET_LEAD.getCode())){
				addActionError("销售无权限下载");
				return ERROR;
			}
			// 如果当前登录账号是仓库管理员
			if(op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode())){
		        searchCondition.setRoleType(op.getRoleType());// 角色
		        searchCondition.setOperators(op.getAccountNo());//当前登陆账号
			} else {
				Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
		        String superRole= map.get("superRole");
		        String opRealId =map.get("opRealId");
		        searchCondition.setRoleType(superRole);// 角色
		        searchCondition.setOpId(opRealId);//当前人员id
		        searchCondition.setOneOrgCode(op.getOneagentid());//机构
			}
			int rows = pagenitionService.countSQL(searchCondition);

			searchRsList = pagenitionService.findAllSQL(searchCondition, 0,
					rows);

			searchRsList = dealData(searchRsList, headArray.length);

			setExcelName(new String(reportName.getBytes(), "ISO8859-1"));

			HSSFWorkbook work = iexcelSerivce.excelExport(reportName,
					headArray, searchRsList);
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);

		} catch (Exception e) {
			logger.info("######导出" + reportName + "失败######");
			addActionError(e.getMessage());
			return ERROR;
		} finally {
			closeOutPut(output);
		}

		return SUCCESS;
	}

	private List<Object> dealData(List<Object> searchRsList, int size)
			throws ServiceException {
		List<Object> searchRsListNew = new ArrayList<Object>();

		if (searchRsList == null || searchRsList.size() == 0) {
			return null;
		}
		Iterator iterator = searchRsList.iterator();
		while (iterator.hasNext()) {
			Object[] obj = (Object[]) iterator.next();
			Object[] objNew = new Object[size];

			objNew[0] = Constance.Null2EmptyTrim(obj[0]);
			objNew[1] = Constance.Null2EmptyTrim(obj[7]);
			objNew[2] = Constance.Null2EmptyTrim(obj[8]);
			objNew[3] = Constance.Null2EmptyTrim(obj[12]);

			String brandCode = obj[1] + "";
			String typeCode = obj[2] + "";
			String nameCode = obj[3] + "";
			
			objNew[4] = ConfigMerinfoUtil.getPosBRAND(brandCode);
			objNew[5] = ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode);
			objNew[6] = ConfigMerinfoUtil.getTerminalType(typeCode);
			
			//objNew[7] = getOrgName(Constance.Null2EmptyTrim(obj[4]));
			objNew[7] = Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[5]))
					.getName();
			objNew[8] = Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[6]))
					.getName();
			objNew[9] = Constance.Null2EmptyTrim(obj[9]);
			objNew[10] = DateUtil.formatTime(Constance.Null2EmptyTrim(obj[10]));
			objNew[11] = DateUtil.formatTime(Constance.Null2EmptyTrim(obj[11]));

			objNew[12] = "";
			if ( !"".equals( Constance.Null2EmptyTrim(obj[13]) ) ){
				objNew[12] = Terminal.valueOfCode(Constance.Null2EmptyTrim(obj[13])).getName();
			}
			searchRsListNew.add(objNew);
		}

		return searchRsListNew;

	}

	private void closeOutPut(ByteArrayOutputStream output)
			throws ServiceException {

		try {
			if (output != null) {
				output.flush();
				output.close();
			}
		} catch (IOException e) {
			logger.error("########导出Excel关闭流失败######", e);
			throw new ServiceException("导出Excel关闭流失败！");
		}
	}

	private String getOrgName(String key) {

		if (orgList == null || "".equals(key)) {
			return "";
		}
		for (TblInsInf bean : orgList) {
			if (key.equals(bean.getInsIdCd()))
				return bean.getInsName();
		}

		return "";

	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TermSnImportSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TERM_SN_IMPORT);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERM_SN_IMPORT,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public TermSnImportSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TermSnImportSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

}
